package controller

import (
	myConfig "common/config"
	"common/helper"
	myredis "common/redis"
	myUserHelp "common/userHelp"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/valyala/fasthttp"
	"math"
	"member/model"
	"strconv"
	"strings"
	"time"
)

type ProxyController struct{}

// 查询直属下级信息
type ProxySubDetailReq struct {
	BeginTime string `json:"beginTime"`
	EndTime   string `json:"endTime"`
	PageIndex int    `json:"pageIndex"`
	PageCount int    `json:"pageCount"`
}

type ProxySubDetailItem struct {
	Uid           int64   `json:"uid" db:"uid" cbor:"uid"`                               //局数
	Valid_waged   float64 `json:"valid_waged" db:"valid_waged" cbor:"valid_waged"`       //有效流水
	TeamNum       int     `json:"team_num" db:"team_num" cbor:"team_num"`                //直属下级人数
	DepositAmount float64 `json:"deposit" db:"deposit" cbor:"deposit"`                   //有效流水
	State         int32   `json:"state" db:"state" cbor:"state"`                         //有效流水
	LoginTime     string  `json:"last_login_at" db:"last_login_at" cbor:"last_login_at"` //有效流水
}

type ProxySubDetailRes struct {
	//汇总数据
	TotalCount int32 `json:"TotalCount" db:"TotalCount"`

	//直属充值人数 	直属有效流水 直属充值金额
	DirectDepositNum    int32   `json:"DirectDepositNum" db:"DirectDepositNum"`
	DirectValidWaged    float64 `json:"DirectValidWaged" db:"DirectValidWaged"`
	DirectDepositAmount float64 `json:"DirectDepositAmount" db:"DirectDepositAmount"`

	OtherDepositNum    int32   `json:"OtherDepositNum" db:"OtherDepositNum"`
	OtherValidWaged    float64 `json:"OtherValidWaged" db:"OtherValidWaged"`
	OhterDepositAmount float64 `json:"OhterDepositAmount" db:"OhterDepositAmount"`

	LstData []ProxySubDetailItem
}

func (that ProxyController) QueryProxyDailySubDetail(ctx *fasthttp.RequestCtx) {
	uid := model.GetUidFromToken(ctx)
	param := ProxySubDetailReq{}

	dataBody := ctx.PostBody()
	err := json.Unmarshal(dataBody, &param)
	if err != nil {
		helper.Print(ctx, false, helper.ParamErr)
		return
	}

	if param.PageIndex < 0 {
		helper.Print(ctx, false, errors.New(helper.LimitExceed))
		return
	}

	var data ProxySubDetailRes
	field := "a.uid,IFNULL(b.p,0) as deposit,IFNULL(b.v,0) as valid_waged, IFNULL(c.x,0) as team_num,e.state,e.last_login_at"
	where := "1=1"

	order := "uid desc"
	table := "(SELECT uid,parent_id FROM tbl_proxy_base WHERE parent_id='" + uid + "')"
	join := ""
	join += " join (SELECT uid,state,last_login_at FROM tbl_member_base) as e on a.uid = e.uid"
	join += " join (SELECT uid,IFNULL(sum(deposit - hidden_deposit_amount),0) as  p,IFNULL(sum(valid_waged),0) as  v from tbl_report_user_daily where created_at>='" + param.BeginTime + "' and created_at<='" + param.EndTime + "' and (valid_waged > 0 or deposit > 0) GROUP BY uid) as b ON a.uid=b.uid"
	join += " left join (SELECT uid,IFNULL(sum(team_num),0) as x from tbl_report_proxy_daily where created_at>='" + param.BeginTime + "' and created_at<='" + param.EndTime + "' and level=1  GROUP BY uid HAVING x>0) as c on a.uid=c.uid"
	offset := (param.PageIndex) * param.PageCount

	count := "select count(1) from " + table + " as a " + join + " where " + where
	err = model.GetSlaveDBInstance().Get(&data.TotalCount, count)
	if err != nil && err.Error() != "sql: no rows in result set" {
		helper.SqlSelectErrLog("%s---%s", count, err.Error())
	}

	query := "select " + field + " from " + table + " as a " + join + " where " + where + " order by " + order + " limit " + strconv.Itoa(param.PageCount) + " offset " + strconv.Itoa(offset)
	err = model.GetSlaveDBInstance().Select(&data.LstData, query)
	if err != nil && err.Error() != "sql: no rows in result set" {
		helper.SqlSelectErrLog("%s---%s", query, err.Error())
	}

	//查询	直属充值人数 	直属有效流水 直属充值金额
	sqlSelect := fmt.Sprintf("select IFNULL(sum(first_deposit_num),0) as DirectDepositNum,"+
		"	IFNULL(sum(deposit - hidden_deposit_amount),0) as DirectDepositAmount,"+
		"	IFNULL(sum(valid_waged),0) as DirectValidWaged"+
		"	from tbl_report_proxy_daily "+
		"	where uid=%s and level=1 "+
		"	and created_at>='%s' and created_at<='%s'", uid, param.BeginTime, param.EndTime)
	err = model.GetSlaveDBInstance().Get(&data, sqlSelect)
	if err != nil && err.Error() != "sql: no rows in result set" {
		helper.SqlSelectErrLog("%s---%s", sqlSelect, err.Error())
	}
	sqlSelect = fmt.Sprintf("select IFNULL(sum(first_deposit_num),0) as OtherDepositNum,"+
		"	IFNULL(sum(deposit - hidden_deposit_amount),0) as OhterDepositAmount,"+
		"	IFNULL(sum(valid_waged),0) as OtherValidWaged"+
		"	from tbl_report_proxy_daily "+
		"	where uid=%s and level>1 "+
		"	and created_at>='%s' and created_at<='%s'", uid, param.BeginTime, param.EndTime)
	err = model.GetSlaveDBInstance().Get(&data, sqlSelect)
	if err != nil && err.Error() != "sql: no rows in result set" {
		helper.SqlSelectErrLog("%s---%s", sqlSelect, err.Error())
	}

	helper.Print(ctx, true, data)
}

// 查询直属下级游戏记录
type ChildGameRecordReq struct {
	BeginTime string `json:"beginTime"`
	EndTime   string `json:"endTime"`
	PageIndex int32  `json:"pageIndex"`
	PageCount int32  `json:"pageCount"`
}

type ChildGameRecordItem struct {
	Uid        int64   `json:"uid" db:"uid" cbor:"uid"`                         //局数
	GameRound  int64   `json:"game_round" db:"game_round" cbor:"game_round"`    //局数
	ValidWaged float64 `json:"valid_waged" db:"valid_waged" cbor:"valid_waged"` //有效流水
	TeamNum    int     `json:"team_num" db:"team_num" cbor:"team_num"`          //直属下级人数
}

type ChildGameRecordRes struct {
	TotalCount    int     `json:"TotalCount" db:"TotalCount"`
	DirectRunning float64 `json:"DirectRunning" db:"DirectRunning" cbor:"DirectRunning"` //直属流水
	OtherRunning  float64 `json:"OtherRunning" db:"OtherRunning" cbor:"OtherRunning"`    //其他流水
	LstData       []ChildGameRecordItem
}

func (that ProxyController) QueryChildGameRecord(ctx *fasthttp.RequestCtx) {
	uid := model.GetUidFromToken(ctx)
	param := ChildGameRecordReq{}

	dataBody := ctx.PostBody()
	err := json.Unmarshal(dataBody, &param)
	if err != nil {
		helper.Print(ctx, false, helper.ParamErr)
		return
	}

	if param.PageIndex < 0 {
		helper.Print(ctx, false, errors.New(helper.LimitExceed))
		return
	}

	var data ChildGameRecordRes
	sqlSelect := fmt.Sprintf("SELECT count(distinct(a.uid))"+
		"	FROM tbl_report_user_daily as a"+
		"	left JOIN tbl_proxy_base as b"+
		"	on a.uid=b.uid"+
		"	where a.created_at>='%s' and a.created_at<='%s' and (a.game_round>0 or a.valid_waged > 0) and  b.parent_id=%s ",
		param.BeginTime, param.EndTime, uid)

	err = model.GetSlaveDBInstance().Get(&data.TotalCount, sqlSelect)
	if err != nil && err.Error() != "sql: no rows in result set" {
		helper.SqlSelectErrLog("%s---%s", sqlSelect, err.Error())
	}

	sqlSelect = fmt.Sprintf("select IFNULL(sum(valid_waged),0) from tbl_report_proxy_daily "+
		"where uid=%s and level=1 "+
		"and created_at>='%s' and created_at<='%s'", uid, param.BeginTime, param.EndTime)
	model.GetSlaveDBInstance().Get(&data.DirectRunning, sqlSelect)

	sqlSelect = fmt.Sprintf("select IFNULL(sum(valid_waged),0) from tbl_report_proxy_daily "+
		"where uid=%s and level>1 "+
		"and created_at>='%s' and created_at<='%s'", uid, param.BeginTime, param.EndTime)
	model.GetSlaveDBInstance().Get(&data.OtherRunning, sqlSelect)

	//先查询在时间范围内 直属下级的有效流水与局数
	sqlSelect = fmt.Sprintf("SELECT a.uid,"+
		"	IFNULL(sum(a.game_round),0) as game_round,"+
		"	IFNULL(sum(a.valid_waged),0) as valid_waged"+
		"	FROM tbl_report_user_daily as a"+
		"	left JOIN tbl_proxy_base as b"+
		"	on a.uid=b.uid"+
		"	where a.created_at>='%s' and a.created_at<='%s' and (a.game_round>0 or a.valid_waged > 0) and  b.parent_id=%s "+
		"	group by a.uid order by a.uid",
		param.BeginTime, param.EndTime, uid)
	sqlSelect += fmt.Sprintf("  LIMIT %d OFFSET %d", param.PageCount, param.PageIndex*param.PageCount)
	selectErr := model.GetSlaveDBInstance().Select(&data.LstData, sqlSelect)

	if len(data.LstData) > 0 {
		var Uids []string
		for _, DataItem := range data.LstData {
			Uids = append(Uids, strconv.FormatInt(DataItem.Uid, 10))
		}

		type tt1 struct {
			Uid     int64 `json:"uid" db:"uid" cbor:"uid"`                //局数
			TeamNum int   `json:"team_num" db:"team_num" cbor:"team_num"` //直属下级人数
		}

		SqlUid := strings.Join(Uids, ",")
		sqlSelect = fmt.Sprintf("Select uid,IFNULL(sum(team_num),0) as team_num from tbl_report_proxy_daily "+
			"	where created_at>='%s' "+
			"	and created_at<='%s' "+
			"	and level=1"+
			"	and uid in(%s) "+
			"	group by uid",
			param.BeginTime, param.EndTime, SqlUid)

		var lsttt1 []tt1
		model.GetSlaveDBInstance().Select(&lsttt1, sqlSelect)

		for index, _ := range data.LstData {
			for _, tt1Item := range lsttt1 {
				if data.LstData[index].Uid == tt1Item.Uid {
					data.LstData[index].TeamNum = tt1Item.TeamNum
					break
				}
			}
		}

	}

	if selectErr != nil {
		helper.SqlSelectErrLog("QueryChildGameRecord error: %s,\n %s", selectErr.Error(), sqlSelect)
	}

	helper.Print(ctx, true, data)
}

type QuueryTimeSecReq struct {
	BeginTime string `json:"beginTime"`
	EndTime   string `json:"endTime"`
}

type ProxyDailyWageReturnRes struct {
	BalanceDate      int64   `json:"BalanceDate" db:"BalanceDate" cbor:"BalanceDate"`                //结算日期 时间戳
	TotalWageReturn  float64 `json:"TotalWageReturn" db:"TotalWageReturn" cbor:"TotalWageReturn"`    //总流水返利
	DirectWageReturn float64 `json:"DirectWageReturn" db:"DirectWageReturn" cbor:"DirectWageReturn"` //直属流水返利
	OtherWageReturn  float64 `json:"OtherWageReturn" db:"OtherWageReturn" cbor:"OtherWageReturn"`    //其他流水返利

	DirectTeamNum int64 `json:"teamlv1_num" db:"teamlv1_num" cbor:"team_num"`   //直属人数
	OtherTeamNum  int64 `json:"teamlv23_num" db:"teamlv23_num" cbor:"team_num"` //其他人数
}

func (that ProxyController) QueryProxyDailyCommi(ctx *fasthttp.RequestCtx) {
	uid := model.GetUidFromToken(ctx)

	param := QuueryTimeSecReq{}

	dataBody := ctx.PostBody()
	err := json.Unmarshal(dataBody, &param)
	if err != nil {
		helper.Print(ctx, false, helper.ParamErr)
		return
	}

	SqlOrder := " order by created_at desc"
	SqlDataWhere := fmt.Sprintf("and created_at>='%s' and created_at<='%s' ", param.BeginTime, param.EndTime)
	//先查询所有的时间
	SqlDate := fmt.Sprintf("SELECT distinct(UNIX_TIMESTAMP(created_at)) from tbl_report_proxy_daily where uid=%s ", uid)
	SqlDate += SqlDataWhere
	SqlDate += SqlOrder
	var BalanceDate []int64
	model.GetSlaveDBInstance().Select(&BalanceDate, SqlDate)

	SqlOrder = " group by created_at order by created_at desc"
	SqlSelect := fmt.Sprintf("SELECT UNIX_TIMESTAMP(created_at) as BalanceDate,ChildWagedReturn as DirectWageReturn,team_num as teamlv1_num"+
		" from tbl_report_proxy_daily where uid=%s and level= 1 ", uid)
	SqlSelect += SqlDataWhere
	SqlSelect += SqlOrder
	var lv1 []ProxyDailyWageReturnRes
	model.GetSlaveDBInstance().Select(&lv1, SqlSelect)

	SqlOrder = " group by created_at order by created_at desc"
	SqlSelect = fmt.Sprintf("SELECT UNIX_TIMESTAMP(created_at) as BalanceDate,"+
		"	IFNULL(sum(ChildWagedReturn),0) as OtherWageReturn, "+
		"	IFNULL(sum(team_num),0) as teamlv23_num"+
		" 	from tbl_report_proxy_daily where uid=%s and level> 1 ", uid)
	SqlSelect += SqlDataWhere
	SqlSelect += SqlOrder
	var lv23 []ProxyDailyWageReturnRes
	model.GetSlaveDBInstance().Select(&lv23, SqlSelect)

	var lvTotal []ProxyDailyWageReturnRes
	for _, DateTimeStamp := range BalanceDate {
		var ItemRes ProxyDailyWageReturnRes
		ItemRes.BalanceDate = DateTimeStamp
		lvTotal = append(lvTotal, ItemRes)
	}

	//处理1级
	for _, lv1Item := range lv1 {
		for i, _ := range lvTotal {
			if lv1Item.BalanceDate == lvTotal[i].BalanceDate {
				lvTotal[i].TotalWageReturn += lv1Item.DirectWageReturn
				lvTotal[i].DirectWageReturn = lv1Item.DirectWageReturn
				lvTotal[i].DirectTeamNum = lv1Item.DirectTeamNum
				break
			}
		}
	}

	for _, lv23Item := range lv23 {
		for i, _ := range lvTotal {
			if lv23Item.BalanceDate == lvTotal[i].BalanceDate {
				lvTotal[i].TotalWageReturn += lv23Item.OtherWageReturn
				lvTotal[i].OtherWageReturn = lv23Item.OtherWageReturn
				lvTotal[i].OtherTeamNum = lv23Item.OtherTeamNum
				break
			}
		}
	}

	var SendDt []ProxyDailyWageReturnRes

	for _, validData := range lvTotal {
		if validData.DirectWageReturn > 0.0 || validData.OtherWageReturn > 0.0 {
			SendDt = append(SendDt, validData)
		}
	}

	helper.Print(ctx, true, SendDt)
}

type ProxyDailyRunningRes struct {
	BalanceDate   int64   `json:"BalanceDate" db:"BalanceDate" cbor:"BalanceDate"`       //结算日期 时间戳
	TotalRunning  float64 `json:"TotalRunning" db:"TotalRunning" cbor:"TotalRunning"`    //总流水
	DirectRunning float64 `json:"DirectRunning" db:"DirectRunning" cbor:"DirectRunning"` //直属流水
	OtherRunning  float64 `json:"OtherRunning" db:"OtherRunning" cbor:"OtherRunning"`    //其他流水
}

// 代理日表 每天流水
func (that ProxyController) QueryProxyDailyRunning(ctx *fasthttp.RequestCtx) {
	uid := model.GetUidFromToken(ctx)
	param := QuueryTimeSecReq{}

	dataBody := ctx.PostBody()
	err := json.Unmarshal(dataBody, &param)
	if err != nil {
		helper.Print(ctx, false, helper.ParamErr)
		return
	}

	SqlOrder := " order by created_at desc"
	SqlDataWhere := fmt.Sprintf("and created_at>='%s' and created_at<='%s' ", param.BeginTime, param.EndTime)
	//先查询所有的时间
	SqlDate := fmt.Sprintf("SELECT distinct(UNIX_TIMESTAMP(created_at)) from tbl_report_proxy_daily where uid=%s ", uid)
	SqlDate += SqlDataWhere
	SqlDate += SqlOrder
	var BalanceDate []int64
	model.GetSlaveDBInstance().Select(&BalanceDate, SqlDate)

	SqlOrder = "  group by created_at order by created_at desc"
	SqlSelect := fmt.Sprintf("SELECT UNIX_TIMESTAMP(created_at) as BalanceDate,"+
		"	IFNULL(sum(valid_waged),0) as DirectRunning "+
		"	from tbl_report_proxy_daily where uid=%s and level= 1 ", uid)
	SqlSelect += SqlDataWhere
	SqlSelect += SqlOrder
	var lv1 []ProxyDailyRunningRes
	model.GetSlaveDBInstance().Select(&lv1, SqlSelect)

	SqlOrder = "  group by created_at order by created_at desc"
	SqlSelect = fmt.Sprintf("SELECT UNIX_TIMESTAMP(created_at) as BalanceDate,"+
		"	IFNULL(sum(valid_waged),0) as OtherRunning "+
		"	from tbl_report_proxy_daily where uid=%s and level> 1 ", uid)
	SqlSelect += SqlDataWhere
	SqlSelect += SqlOrder
	var lv23 []ProxyDailyRunningRes
	model.GetSlaveDBInstance().Select(&lv23, SqlSelect)

	var lvTotal []ProxyDailyRunningRes
	for _, DateTimeStamp := range BalanceDate {
		var ItemRes ProxyDailyRunningRes
		ItemRes.BalanceDate = DateTimeStamp
		lvTotal = append(lvTotal, ItemRes)
	}

	//处理1级
	for _, lv1Item := range lv1 {
		for i, _ := range lvTotal {
			if lv1Item.BalanceDate == lvTotal[i].BalanceDate {
				lvTotal[i].TotalRunning += lv1Item.DirectRunning
				lvTotal[i].DirectRunning = lv1Item.DirectRunning
				break
			}
		}
	}

	for _, lv23Item := range lv23 {
		for i, _ := range lvTotal {
			if lv23Item.BalanceDate == lvTotal[i].BalanceDate {
				lvTotal[i].TotalRunning += lv23Item.OtherRunning
				lvTotal[i].OtherRunning = lv23Item.OtherRunning
				break
			}
		}
	}

	var SendDt []ProxyDailyRunningRes

	for _, validData := range lvTotal {
		if validData.DirectRunning > 0.0 || validData.OtherRunning > 0.0 {
			SendDt = append(SendDt, validData)
		}
	}

	helper.Print(ctx, true, SendDt)
}

type ProxyAccuInfo struct {
	TotalCommi      float64 `json:"TotalCommi" db:"TotalCommi" cbor:"TotalCommi"`                   //总佣金
	TeamNum         float64 `json:"team_num" db:"team_num" cbor:"team_num"`                         //邀请人数
	DepositNum      int     `json:"DepositNum" db:"DepositNum" cbor:"DepositNum"`                   //充值人数
	ValidNum        float64 `json:"ValidNum" db:"ValidNum" cbor:"ValidNum"`                         //有效人数
	Deposit         float64 `json:"Deposit" db:"Deposit" cbor:"Deposit"`                            //总充值金额
	Running         float64 `json:"Running" db:"Running" cbor:"Running"`                            //总流水
	OtherDeposit    float64 `json:"OtherDeposit" db:"OtherDeposit" cbor:"OtherDeposit"`             //2+3级玩家的下级充值总额
	OtherDepositNum float64 `json:"OtherDepositNum" db:"OtherDepositNum" OtherDepositNum:"Running"` //2+3级玩家的充值人数
	OtherRunning    float64 `json:"OtherRunning" db:"OtherRunning" cbor:"OtherRunning"`             //1,2,3级团队总打码
}

func GetAccuInfoFromSql(valUid string) (ProxyAccuInfo, bool) {
	var tAccuInfo ProxyAccuInfo
	sqlSelect := fmt.Sprintf("select proxy_invite_bonus,team_num,deposit_num,valid_num,deposit,valid_waged from tbl_proxy_accu where uid=%s and level=1", valUid)
	rows, err := model.GetSlaveDBInstance().Query(sqlSelect)
	if err != nil {
		return tAccuInfo, false
	}

	for rows.Next() {
		rows.Scan(&tAccuInfo.TotalCommi, &tAccuInfo.TeamNum,
			&tAccuInfo.DepositNum, &tAccuInfo.ValidNum, &tAccuInfo.Deposit, &tAccuInfo.Running)
	}

	//减去隐藏的充值额
	var sqlSelHiddenDeposit string
	sqlSelHiddenDeposit = fmt.Sprintf("SELECT IFNULL(SUM(hidden_amount), 0) from tbl_deposit where parent_id=%s and (state=362 or state=365) ", valUid)
	var fDepositHidden float64
	model.GetSlaveDBInstance().Get(&fDepositHidden, sqlSelHiddenDeposit)
	tAccuInfo.Deposit -= fDepositHidden

	sqlSelect = fmt.Sprintf("select IFNULL(sum(deposit - hidden_deposit_amount),0) as OtherDeposit,"+
		"	IFNULL(sum(deposit_num),0) as OtherDepositNum,"+
		"	IFNULL(sum(valid_waged),0) as OtherRunning "+
		"	from tbl_proxy_accu where uid=%s and level>1", valUid)
	rows, err = model.GetSlaveDBInstance().Query(sqlSelect)
	if err != nil {
		return tAccuInfo, false
	}

	for rows.Next() {
		rows.Scan(&tAccuInfo.OtherDeposit, &tAccuInfo.OtherDepositNum, &tAccuInfo.OtherRunning)
	}

	tAccuInfo.OtherRunning += tAccuInfo.Running
	return tAccuInfo, true
}

func (that ProxyController) QueryAccuInfo(ctx *fasthttp.RequestCtx) {
	valUid := model.GetUidFromToken(ctx)
	if valUid == "" {
		helper.Print(ctx, false, errors.New(helper.AccessTokenExpires))
		return
	}

	tAccuInfo, bReturn := GetAccuInfoFromSql(valUid)
	helper.Print(ctx, bReturn, tAccuInfo)
}

/*
查询代理周佣金
*/

type WeekDepositItem struct {
	LastWeekDepositReturn float64 `json:"LastWeekDepositReturn" db:"LastWeekDepositReturn" cbor:"LastWeekDepositReturn"`
	WeekDeposit           float64 `json:"WeekDeposit" db:"WeekDeposit" cbor:"WeekDeposit"`
	LastDeposit           float64 `json:"LastDeposit" db:"LastDeposit" cbor:"LastDeposit"`
}

func (that ProxyController) QueryProxyCommiReturn(ctx *fasthttp.RequestCtx) {
	valUid := model.GetUidFromToken(ctx)
	if valUid == "" {
		helper.Print(ctx, false, errors.New(helper.AccessTokenExpires))
		return
	}

	var queryItem WeekDepositItem
	queryItem.LastWeekDepositReturn = GetProxyCommiReturnFromDB(valUid)

	now := time.Now()
	daysUntilMonday := int(now.Weekday() - time.Monday)
	if daysUntilMonday < 0 {
		daysUntilMonday += 7
	}

	// 周一的时间
	monday := now.AddDate(0, 0, -daysUntilMonday).Format("2006-01-02") + " 00:00:00"
	loc, _ := time.LoadLocation("America/Sao_Paulo")
	t, _ := time.ParseInLocation("2006-01-02 15:04:05", monday, loc)

	lastWeekMonday := t.AddDate(0, 0, -7)
	sqlSelect := fmt.Sprintf("select IFNULL(SUM(amount-hidden_amount), 0) from tbl_deposit "+
		" where parent_id=%s and (state=362 or state=365) and created_at>=%d",
		valUid, t.Unix())
	model.GetSlaveDBInstance().Get(&queryItem.WeekDeposit, sqlSelect)

	sqlSelect = fmt.Sprintf("select IFNULL(SUM(amount-hidden_amount), 0) from tbl_deposit "+
		" where parent_id=%s and (state=362 or state=365) and created_at>=%d and created_at<%d",
		valUid, lastWeekMonday.Unix(), t.Unix())

	model.GetSlaveDBInstance().Get(&queryItem.LastDeposit, sqlSelect)

	helper.Print(ctx, true, queryItem)
}

func GetProxyCommiReturnFromDB(valUid string) float64 {
	var fWeekDepositReturn float64

	fWeekDepositReturn = 0.0
	sqlSelect := fmt.Sprintf("select week_proxy_commi_return from tbl_member_return where uid=%s", valUid)
	rows, err := model.GetMasterDBInstance().Query(sqlSelect)
	if err != nil {
		return fWeekDepositReturn
	}

	for rows.Next() {
		rows.Scan(&fWeekDepositReturn)
	}

	return fWeekDepositReturn
}

type ProxyTeamData struct {
	Uid        int32   `json:"uid" db:"UID" cbor:"uid"`
	CreateTime string  `json:"created_at" db:"created_at" cbor:"created_at"`
	Running    float64 `json:"running" db:"running" cbor:"running"`    //总流水
	Deposit    float64 `json:"deposit" db:"deposit" cbor:"deposit"`    //总流水
	VipLevel   float64 `json:"VipLevel" db:"VipLevel" cbor:"VipLevel"` //VipLevel
}

/*
查询代理等级信息
*/

type TeamDataParam struct {
	BeginTime string `json:"beginTime"`
	EndTime   string `json:"endTime"`
	PageIndex int32  `json:"pageIndex"`
	PageCount int32  `json:"pageCount"`
	Uid       int32  `json:"Uid"`
}

type ProxyChildItem struct {
	ChildDeposit           float64 `json:"ChildDeposit" db:"Deposit" cbor:"ChildCounts"`                   //直属下级充值金额
	OtherDeposit           float64 `json:"OtherDeposit" db:"OtherDeposit" cbor:"OtherCounts"`              //二三级充值金额
	ChildFirstDepositCount float64 `json:"ChildFirstDepositCount" db:"DepositNum" cbor:"ChildWaged"`       //直属下级充值人数
	OtherFirstDepositCount float64 `json:"OtherFirstDepositCount" db:"OtherDepositNum" cbor:"OtherdWaged"` //二三级流水充值人数
}

type QueryTeamData struct {
	TAccuInfo    ProxyChildItem
	TotalCount   int `json:"TotalCount" db:"TotalCount"`
	ListTeamData []ProxyTeamData
}

/*
1级下级提款记录
*/
type ChildWithdrawItem struct {
	Uid       float64 `json:"uid" db:"uid" cbor:"uid"`
	BillNo    string  `json:"oid" db:"oid" cbor:"oid"`
	Amount    float64 `json:"amount" db:"amount" cbor:"Amount"`
	ConfirmAt int32   `json:"confirm_at" db:"confirm_at" cbor:"confirm_at"`
}

type ChildWithdrawResult struct {
	TotalCount   int `json:"TotalCount" db:"TotalCount"`
	ListTeamData []ChildWithdrawItem
}

type ChildWithdrawParam struct {
	PageIndex int32 `json:"pageIndex"`
	PageCount int32 `json:"pageCount"`
}

/*
查询本周下级的充值记录
*/

// 下级充值
type SubDepositRecordItem struct {
	Uid        float64 `json:"uid" db:"uid" cbor:"uid"`
	Amount     float64 `json:"amount" db:"amount" cbor:"amount"`
	CreateTime int32   `json:"created_at" db:"created_at" cbor:"created_at"`
}

func (that ProxyController) QuerythisWeekDepositRecord(ctx *fasthttp.RequestCtx) {
	valUid := model.GetUidFromToken(ctx)
	if valUid == "" {
		helper.Print(ctx, false, errors.New(helper.AccessTokenExpires))
		return
	}

	now := time.Now()
	daysUntilMonday := int(now.Weekday() - time.Monday)
	if daysUntilMonday < 0 {
		daysUntilMonday += 7
	}

	// 周一的时间
	monday := now.AddDate(0, 0, -daysUntilMonday).Format("2006-01-02") + " 00:00:00"
	loc, _ := time.LoadLocation("America/Sao_Paulo")
	t, _ := time.ParseInLocation("2006-01-02 15:04:05", monday, loc)

	sqlSelect := fmt.Sprintf("select uid,(amount-hidden_amount) as amount,created_at from tbl_deposit where parent_id=%s and  (state=362 or state=365) and hidden=0 and confirm_at>=%d order by created_at desc",
		valUid, t.Unix())

	var DepositRecord []SubDepositRecordItem
	model.GetSlaveDBInstance().Select(&DepositRecord, sqlSelect)

	helper.Print(ctx, true, DepositRecord)

}

func (that ProxyController) QuerylastWeekDepositRecord(ctx *fasthttp.RequestCtx) {
	valUid := model.GetUidFromToken(ctx)
	if valUid == "" {
		helper.Print(ctx, false, errors.New(helper.AccessTokenExpires))
		return
	}

	now := time.Now()
	daysUntilMonday := int(now.Weekday() - time.Monday)
	if daysUntilMonday < 0 {
		daysUntilMonday += 7
	}

	// 周一的时间
	// 周一的时间
	monday := now.AddDate(0, 0, -daysUntilMonday).Format("2006-01-02") + " 00:00:00"
	loc, _ := time.LoadLocation("America/Sao_Paulo")
	t, _ := time.ParseInLocation("2006-01-02 15:04:05", monday, loc)

	lastWeekMonday := t.AddDate(0, 0, -7)

	sqlSelect := fmt.Sprintf("select uid,(amount-hidden_amount) as amount,created_at from tbl_deposit where parent_id=%s and  (state=362 or state=365) and hidden=0 and confirm_at>=%d and confirm_at<%d ",
		valUid, lastWeekMonday.Unix(), t.Unix())

	var DepositRecord []SubDepositRecordItem
	model.GetSlaveDBInstance().Select(&DepositRecord, sqlSelect)

	helper.Print(ctx, true, DepositRecord)
}

func (that ProxyController) QueryChildWithdraw(ctx *fasthttp.RequestCtx) {
	uid := model.GetUidFromToken(ctx)
	param := ChildWithdrawParam{}

	dataBody := ctx.PostBody()
	err := json.Unmarshal(dataBody, &param)
	if err != nil {
		helper.Print(ctx, false, helper.ParamErr)
		return
	}

	if param.PageIndex < 0 {
		helper.Print(ctx, false, errors.New(helper.LimitExceed))
		return
	}

	var data ChildWithdrawResult
	sqlSelect := fmt.Sprintf("SELECT IFNULL(COUNT(1),0) FROM tbl_withdraw where parent_id=%s AND state IN (374,376)", uid)
	selectErr := model.GetSlaveDBInstance().Get(&data.TotalCount, sqlSelect)

	if selectErr != nil {
		helper.SqlSelectErrLog("QueryChildWithdraw error: %s,\n %s", selectErr.Error(), sqlSelect)
	}

	sqlSelect = fmt.Sprintf("SELECT uid,oid,amount,confirm_at FROM tbl_withdraw where parent_id=%s  AND state IN (374,376)  ORDER BY confirm_at DESC LIMIT %d OFFSET %d",
		uid, param.PageCount, (param.PageIndex)*param.PageCount)

	selectErr = model.GetSlaveDBInstance().Select(&data.ListTeamData, sqlSelect)

	if selectErr != nil {
		helper.SqlSelectErrLog("QueryChildWithdraw error: %s,\n %s", selectErr.Error(), sqlSelect)
	}

	helper.Print(ctx, true, data)
}
func (that ProxyController) QueryTeamData(ctx *fasthttp.RequestCtx) {
	uid := model.GetUidFromToken(ctx)
	param := TeamDataParam{}

	dataBody := ctx.PostBody()
	err := json.Unmarshal(dataBody, &param)
	if err != nil {
		helper.Print(ctx, false, helper.ParamErr)
		return
	}

	lockKey := uid + "queryTeamData"
	if !myredis.Lock(model.GetRedisInstance(), lockKey) {
		helper.GetloggerInstance().Criticalf("lockError:%s", lockKey)
		return
	}
	defer myredis.Unlock(model.GetRedisInstance(), lockKey)

	if param.PageIndex < 0 {
		helper.Print(ctx, false, errors.New(helper.LimitExceed))
		return
	}

	sqlSelect := fmt.Sprintf("select count(1) from ( SELECT a.UID"+
		"	FROM tbl_proxy_base AS a"+
		"	left JOIN tbl_report_user_daily as b"+
		"	on a.UID=b.uid"+
		"	WHERE (b.valid_waged > 0 or b.deposit > 0) AND a.parent_id=%s"+
		"	and b.created_at>='%s' and b.created_at<='%s'", uid, param.BeginTime, param.EndTime)

	if param.Uid > 0 {
		sqlSelect += fmt.Sprintf("  and a.UID=%d", param.Uid)
	}

	sqlSelect += " group by a.uid) as tt"

	var data QueryTeamData
	err = model.GetSlaveDBInstance().Get(&data.TotalCount, sqlSelect)
	if err != nil && err.Error() != "sql: no rows in result set" {
		helper.SqlSelectErrLog("%s---%s", sqlSelect, err.Error())
	}

	sqlSelect = fmt.Sprintf("SELECT a.UID,CONVERT(a.created_at,CHAR) as created_at, IFNULL(sum(b.valid_waged),0) as running,"+
		"	IFNULL(sum(b.deposit),0) as deposit,"+
		"	c.level as VipLevel"+
		"	FROM tbl_proxy_base AS a"+
		"	left JOIN tbl_report_user_daily as b"+
		"	on a.UID=b.uid"+
		"	left JOIN tbl_member_vip as c"+
		"	on a.UID=c.uid"+
		"	WHERE (b.valid_waged > 0 or b.deposit > 0) AND a.parent_id=%s"+
		"	and b.created_at>='%s' and b.created_at<='%s'", uid, param.BeginTime, param.EndTime)

	if param.Uid > 0 {
		sqlSelect += fmt.Sprintf("  and a.UID=%d", param.Uid)
	}

	sqlSelect += " group by a.uid"
	sqlSelect += fmt.Sprintf("  LIMIT %d OFFSET %d", param.PageCount, param.PageIndex*param.PageCount)

	err = model.GetSlaveDBInstance().Select(&data.ListTeamData, sqlSelect)

	if err != nil && err.Error() != "sql: no rows in result set" {
		helper.SqlSelectErrLog("%s---%s", sqlSelect, err.Error())
	}

	sqlSelect = fmt.Sprintf("SELECT  "+
		"IFNULL(SUM(CASE WHEN b.first_deposit > 0 THEN 1 ELSE 0 END),0) AS  DepositNum, "+
		"IFNULL(sum(b.deposit),0) as Deposit	"+
		"FROM tbl_proxy_base AS a	left JOIN tbl_report_user_daily as b	"+
		"on a.UID=b.uid	"+
		"WHERE (b.valid_waged > 0 or b.deposit > 0) "+
		"AND a.parent_id=%s	"+
		"and b.created_at>='%s' and b.created_at<='%s'", uid, param.BeginTime, param.EndTime)
	if param.Uid > 0 {
		sqlSelect += fmt.Sprintf("  and a.UID=%d", param.Uid)
	}

	err = model.GetSlaveDBInstance().Get(&data.TAccuInfo, sqlSelect)
	if err != nil && err.Error() != "sql: no rows in result set" {
		helper.SqlSelectErrLog("%s---%s", sqlSelect, err.Error())
	}

	loc, _ := time.LoadLocation("America/Sao_Paulo")
	StartTimeInt, _ := helper.TimeToLocMs(param.BeginTime, loc)
	StartTimeInt = StartTimeInt / 1000
	EndTimeInt, _ := helper.TimeToLocMs(param.EndTime, loc)
	EndTimeInt = EndTimeInt / 1000

	//减去1级隐藏的充值额
	for k, teamData := range data.ListTeamData {
		var sqlSelHiddenDeposit string
		sqlSelHiddenDeposit = fmt.Sprintf("SELECT IFNULL(SUM(hidden_amount), 0) from tbl_deposit "+
			"where uid=%d and (state=362 or state=365) "+
			" and confirm_at>=%d and confirm_at<=%d ", teamData.Uid, StartTimeInt, EndTimeInt)
		var fDepositHidden float64
		err = model.GetSlaveDBInstance().Get(&fDepositHidden, sqlSelHiddenDeposit)
		data.ListTeamData[k].Deposit -= fDepositHidden
		data.TAccuInfo.ChildDeposit -= fDepositHidden
	}

	sqlSelect = fmt.Sprintf("SELECT  "+
		"IFNULL(SUM(CASE WHEN b.first_deposit > 0 THEN 1 ELSE 0 END),0) AS   OtherDepositNum, "+
		"IFNULL(sum(b.deposit),0) as OtherDeposit	"+
		"FROM tbl_proxy_base AS a	left JOIN tbl_report_user_daily as b	"+
		"on a.UID=b.uid	"+
		"WHERE (b.valid_waged > 0 or b.deposit > 0) "+
		"AND (a.grand_id=%s	or a.great_grand_id=%s) "+
		"and b.created_at>='%s' and b.created_at<='%s'", uid, uid, param.BeginTime, param.EndTime)
	if param.Uid > 0 {
		sqlSelect += fmt.Sprintf("  and a.UID=%d", param.Uid)
	}

	err = model.GetSlaveDBInstance().Get(&data.TAccuInfo, sqlSelect)
	if err != nil && err.Error() != "sql: no rows in result set" {
		helper.SqlSelectErrLog("%s---%s", sqlSelect, err.Error())
	}

	//减去2,3级隐藏的充值额
	sqlSubPlayer := fmt.Sprintf("SELECT uid from tbl_proxy_base where (grand_id=%s or great_grand_id=%s)"+
		" and created_at>='%s' and created_at<='%s' ", uid, uid, param.BeginTime, param.EndTime)
	var UidArray []int32
	err = model.GetSlaveDBInstance().Select(&UidArray, sqlSubPlayer)

	for _, subUid := range UidArray {
		var sqlSelHiddenDeposit string
		sqlSelHiddenDeposit = fmt.Sprintf("SELECT IFNULL(SUM(hidden_amount), 0) from tbl_deposit "+
			"where uid=%d and (state=362 or state=365) "+
			" and confirm_at>=%d and confirm_at<=%d ", subUid, StartTimeInt, EndTimeInt)
		var fDepositHidden float64
		model.GetSlaveDBInstance().Get(&fDepositHidden, sqlSelHiddenDeposit)
		data.TAccuInfo.OtherDeposit -= fDepositHidden
	}

	helper.Print(ctx, true, data)
}

type ValidInviteBonusInfo struct {
	ValidInviteCount int   `json:"ValidInviteCount"` //有效邀请人数
	BonusStatus      int64 `json:"BonusStatus"`      //状态  按位操作
}

func (that ProxyController) GetValidInviteBonusInfo(ctx *fasthttp.RequestCtx) {
	valUid := model.GetUidFromToken(ctx)

	var tInfo ValidInviteBonusInfo

	tInfo.BonusStatus = myUserHelp.GetProxyInviteBonusStatus(valUid)
	var ValidInviteCounts int
	sqlSelect := fmt.Sprintf("SELECT valid_num FROM tbl_proxy_accu WHERE UID=%s and level=1", valUid)
	model.GetMasterDBInstance().Get(&ValidInviteCounts, sqlSelect)

	tInfo.ValidInviteCount = ValidInviteCounts

	helper.Print(ctx, true, tInfo)
	return
}

/*
手动领取用效邀请的奖励
*/

type ValidInviteBonusParam struct {
	BonusStage int `json:"BonusStage"` //
}

func (that ProxyController) AchieveValidInviteBonus(ctx *fasthttp.RequestCtx) {
	param := ValidInviteBonusParam{}
	data := ctx.PostBody()
	err := json.Unmarshal(data, &param)
	if err != nil {
		helper.InfoLog("[AchieveValidInviteBonus:json.Unmarshal]:%s", err.Error())
		helper.Print(ctx, false, helper.ParamErr)
		return
	}

	if myConfig.IsActiveOpen(myConfig.ActiveType_ProxyBonus_ByValidCounts) == 0 {
		helper.Print(ctx, false, helper.AppActiveClose)
		return
	}

	valUid := model.GetUidFromToken(ctx)
	lockKey := valUid + "ValidInviteBonus"
	if !myredis.Lock(model.GetRedisInstance(), lockKey) {
		return
	}

	defer myredis.Unlock(model.GetRedisInstance(), lockKey)
	var ValidInviteCounts int
	sqlSelect := fmt.Sprintf("SELECT valid_num FROM tbl_proxy_accu WHERE UID=%s and level=1", valUid)
	model.GetMasterDBInstance().Get(&ValidInviteCounts, sqlSelect)
	MaxStage := myConfig.GetProxyBonusMaxStage(ValidInviteCounts)
	if param.BonusStage > MaxStage || param.BonusStage <= 0 {
		helper.Print(ctx, false, helper.ParamErr)
		return
	}

	ProxyStage := myUserHelp.GetProxyInviteBonusStatus(valUid)

	if ((1 << (param.BonusStage - 1)) & ProxyStage) != 0 {
		helper.Print(ctx, false, helper.NoAwardCollect)
		return
	}

	nAccuDGBStatus := (1 << (param.BonusStage - 1))
	lastAccuDGBStatus := ProxyStage | (int64(nAccuDGBStatus))
	myUserHelp.SetProxyInviteBonusStatus(valUid, lastAccuDGBStatus)

	ProxyInviteBonus := myConfig.GetProxyInviteBonusByStage(param.BonusStage)

	if myUserHelp.G_UserButton.GetCommiButton(valUid) == myUserHelp.ButtonOpen {
		myUserHelp.AddBalanceTransactionRecord(valUid, ProxyInviteBonus, helper.TransactionInvitationBonus, "0", helper.GenId(), 0.00, "", "", 0)
		myUserHelp.AddUserWageItem(valUid, math.Abs(ProxyInviteBonus), helper.TransactionInvitationBonus)
		myUserHelp.AddTotalProxyInviteBonus(valUid, math.Abs(ProxyInviteBonus))
		myUserHelp.AddUserBalanceByFloat64(valUid, ProxyInviteBonus)
		if ProxyInviteBonus > 0.0 {

			_, errExec := model.GetMasterDBInstance().Exec("CALL tbl_report_user_business_ProxyInviteBonus_update(?,?,?)", valUid, ProxyInviteBonus, time.Now().Unix())
			if errExec != nil {
				helper.GetloggerInstance().Emergencyf("CALL tbl_report_user_business_ProxyInviteBonus_update(%s,%d,%d);	reason:%s", valUid, ProxyInviteBonus,
					time.Now().Unix(), errExec.Error())
			}

			_, errExec = model.GetMasterDBInstance().Exec("CALL tbl_report_user_change_update(?,?,?,?)", valUid, helper.TransactionInvitationBonus, ProxyInviteBonus, time.Now().Unix())
			if errExec != nil {
				helper.GetloggerInstance().Emergencyf("CALL tbl_report_user_change_update(%s,%d,%0.2f,%d);	reason:%s",
					valUid, helper.TransactionInvitationBonus, ProxyInviteBonus, time.Now().Unix(), errExec.Error())
			}
		}

		myredis.ImmediateUpdateRole(valUid)
	}

	helper.Print(ctx, true, ProxyInviteBonus)
}

/*
领取代理周佣金
*/

func (that ProxyController) AchieveProxyCommiReturn(ctx *fasthttp.RequestCtx) {
	valUid := model.GetUidFromToken(ctx)
	if valUid == "" {
		helper.Print(ctx, false, errors.New(helper.AccessTokenExpires))
		return
	}

	myredis.Lock(model.GetRedisInstance(), valUid+"DepositReturn")
	fWeekDepositReturn := GetProxyCommiReturnFromDB(valUid)
	if fWeekDepositReturn == 0.0 {
		helper.Print(ctx, true, fWeekDepositReturn)
		myredis.Unlock(model.GetRedisInstance(), valUid+"DepositReturn")
		return
	}

	if myUserHelp.G_UserButton.GetCommiButton(valUid) == 2 {
		helper.Print(ctx, true, fWeekDepositReturn)
		myredis.Unlock(model.GetRedisInstance(), valUid+"DepositReturn")
		return
	}

	//增加打码
	myUserHelp.AddBalanceTransactionRecord(valUid, fWeekDepositReturn, helper.TransactionWeekCommiReturn, "0", helper.GenId(), 0.00, "", "", 0)
	myUserHelp.AddUserWageItem(valUid, fWeekDepositReturn, helper.TransactionWeekCommiReturn)
	myUserHelp.AddTotalWeekCommiReturn(valUid, fWeekDepositReturn)
	myUserHelp.AddUserBalanceByFloat64(valUid, fWeekDepositReturn)
	helper.Print(ctx, true, fWeekDepositReturn)
	if fWeekDepositReturn > 0.0 {
		_, errExec := model.GetMasterDBInstance().Exec("CALL tbl_report_user_change_update(?,?,?,?)", valUid, helper.TransactionWeekCommiReturn, fWeekDepositReturn, time.Now().Unix())
		if errExec != nil {
			helper.GetloggerInstance().Emergencyf("CALL tbl_report_user_change_update(%s,%d,%0.2f,%d); reason:%s",
				valUid, helper.TransactionWeekCommiReturn, fWeekDepositReturn, time.Now().Unix(), errExec.Error())
		}
	}

	sqlUpdate := fmt.Sprintf("update tbl_member_return set  week_proxy_commi_return = 0.0 where uid=%s", valUid)
	model.GetMasterDBInstance().Exec(sqlUpdate)

	myredis.Unlock(model.GetRedisInstance(), valUid+"DepositReturn")
	helper.Print(ctx, true, fWeekDepositReturn)
}

type ProxyChildDetailInfoParam struct {
	PageIndex int32  `json:"pageIndex"`
	PageCount int32  `json:"pageCount"`
	Username  string `json:"Username"`
	QueryType int    `json:"QueryType"` // 0 全部 1 有效 2 无效
}

type ProxyChildDetailInfo struct {
	Username           string  `json:"username" db:"username" cbor:"username"`                                //昵称
	CreatedAt          int     `json:"createdAt" db:"created_at" cbor:"createdAt"`                            //注册时间
	TotalWaged         float64 `json:"totalWaged" db:"totalWaged" cbor:"totalWaged"`                          //总流水
	FirstDepositAmount float64 `json:"FirstDepositAmount" db:"first_deposit_mount" cbor:"FirstDepositAmount"` //首冲金额
}

type ProxyChildDetailInfoItem struct {
	ValidInviteWagedReq   float64 `json:"ValidInviteWagedReq"`
	ValidInviteMinDeposit float64 `json:"ValidInviteMinDeposit"`
	TotalCount            int     `json:"TotalCount" db:"TotalCount"`
	ListData              []ProxyChildDetailInfo
}

func (that ProxyController) QueryProxyChildDetailInfo(ctx *fasthttp.RequestCtx) {

	uid := model.GetUidFromToken(ctx)
	var dataRet ProxyChildDetailInfoItem

	param := ProxyChildDetailInfoParam{}

	dataBody := ctx.PostBody()
	err := json.Unmarshal(dataBody, &param)
	if err != nil {
		helper.Print(ctx, false, helper.ParamErr)
		return
	}

	dataRet.ValidInviteWagedReq = myConfig.GetGameCfgFloat64(myConfig.CfgValidInviteWagedReq)
	dataRet.ValidInviteMinDeposit = myConfig.GetGameCfgFloat64(myConfig.CfgValidInviteMinDeposit)

	var ChildId int = 0
	if param.Username != "" {
		sqlSelect := fmt.Sprintf("Select uid from tbl_member_base where username='%s'", param.Username)
		err := model.GetMasterDBInstance().Get(&ChildId, sqlSelect)
		if err != nil && err.Error() != "sql: no rows in result set" {
			helper.SqlErrLog("QueryProxyChildDetailInfo:%s---%s", sqlSelect, err.Error())
		}

		if ChildId == 0 {
			helper.Print(ctx, true, dataRet)
			return
		}
	}

	SelField := "SELECT a.username,a.created_at,b.totalWaged,c.first_deposit_mount FROM `tbl_member_base` as a " +
		"	left join tbl_member_accu as b on a.uid=b.uid" +
		"	left join tbl_proxy_base as c on b.uid=c.uid"

	sqlWhere := fmt.Sprintf("	where c.parent_id=%s	", uid)
	if ChildId > 0 {
		sqlWhere += fmt.Sprintf("	and a.uid=%d", ChildId)
	}

	if param.QueryType == 1 {
		sqlWhere += fmt.Sprintf("	and b.totalWaged>=%0.2f and c.first_deposit_mount>=%0.2f", dataRet.ValidInviteWagedReq, dataRet.ValidInviteMinDeposit)
	} else if param.QueryType == 2 {
		sqlWhere += fmt.Sprintf("	and (b.totalWaged<%0.2f or c.first_deposit_mount<%0.2f)", dataRet.ValidInviteWagedReq, dataRet.ValidInviteMinDeposit)
	}

	sqlWhere += fmt.Sprintf("  LIMIT %d OFFSET %d", param.PageCount, (param.PageIndex)*param.PageCount)
	sqlSelect := SelField + sqlWhere

	err = model.GetSlaveDBInstance().Select(&dataRet.ListData, sqlSelect)
	if err != nil && err.Error() != "sql: no rows in result set" {
		helper.SqlErrLog("QueryProxyChildInfo:%s---%s", sqlSelect, err.Error())
	}

	SelCount := "SELECT COUNT(1) FROM `tbl_member_base` as a " +
		"	left join tbl_member_accu as b on a.uid=b.uid" +
		"	left join tbl_proxy_base as c on b.uid=c.uid"
	sqlSelect = SelCount + sqlWhere
	err = model.GetSlaveDBInstance().Get(&dataRet.TotalCount, sqlSelect)
	if err != nil && err.Error() != "sql: no rows in result set" {
		helper.SqlErrLog("QueryProxyChildInfo:%s---%s", sqlSelect, err.Error())
	}

	helper.Print(ctx, true, dataRet)
}

type ProxyChildInfoItem struct {
	ChildCounts          float64 `json:"ChildCounts" db:"team_num" cbor:"ChildCounts"`                       //直属下级人数
	OtherCounts          float64 `json:"OtherCounts" db:"OtherCounts" cbor:"OtherCounts"`                    //二三级人数
	ChildWaged           float64 `json:"ChildWaged" db:"valid_waged" cbor:"ChildWaged"`                      //直属流水
	OtherdWaged          float64 `json:"OtherdWaged" db:"OtherdWaged" cbor:"OtherdWaged"`                    //二三级流水
	ChildWageReturn      float64 `json:"ChildWageReturn" db:"ChildWagedReturn" cbor:"ChildCommi"`            //（直属流水返利）
	OtherWageReturn      float64 `json:"OtherWageReturn" db:"OtherWageReturn" cbor:"OtherCommi"`             //二三级佣金（下级流水返利）
	ChildCommi           float64 `json:"ChildCommi" db:"proxy_invite_bonus" cbor:"ChildCommi"`               //（直属佣金）
	OtherCommi           float64 `json:"OtherCommi" db:"OtherCommi" cbor:"OtherCommi"`                       //二三级佣金
	FirstDepositToParent float64 `json:"enable_first_deposit_to_parent" db:"enable_first_deposit_to_parent"` //首充梯度奖励佣金
}

func (that ProxyController) QueryProxyChildInfo(ctx *fasthttp.RequestCtx) {
	uid := model.GetUidFromToken(ctx)
	var dataRet ProxyChildInfoItem
	sqlSelect := fmt.Sprintf("SELECT team_num,valid_waged,ChildWagedReturn,proxy_invite_bonus,enable_first_deposit_to_parent from tbl_proxy_accu where uid=%s and level=1", uid)

	err := model.GetSlaveDBInstance().Get(&dataRet, sqlSelect)
	if err != nil && err.Error() != "sql: no rows in result set" {
		helper.SqlSelectErrLog("QueryProxyChildInfo11:%s---%s", sqlSelect, err.Error())
	}

	sqlSelect = fmt.Sprintf("SELECT IFNULL(sum(team_num),0) as OtherCounts,"+
		"	IFNULL(sum(valid_waged),0) as OtherdWaged,"+
		"	IFNULL(sum(ChildWagedReturn),0) as OtherWageReturn,"+
		"	IFNULL(sum(proxy_invite_bonus),0)  as OtherCommi"+
		"	from tbl_proxy_accu where uid=%s and level>1", uid)
	err = model.GetSlaveDBInstance().Get(&dataRet, sqlSelect)
	if err != nil && err.Error() != "sql: no rows in result set" {
		helper.SqlSelectErrLog("QueryProxyChildInfo22:%s---%s", sqlSelect, err.Error())
	}

	helper.Print(ctx, true, dataRet)
}

type ProxyDirectChildInfoItem struct {
	TeamCounts           float64 `json:"TeamCounts" db:"TeamCounts" cbor:"TeamCounts"`                         //直属下级人数
	FirstDepositCounts   float64 `json:"FirstDepositCounts" db:"FirstDepositCounts" cbor:"FirstDepositCounts"` //首充人数
	DepositCounts        float64 `json:"DepositCounts" db:"DepositCounts" cbor:"DepositCounts"`                //总充值人数
	DepositNums          float64 `json:"DepositNums" db:"DepositNums" cbor:"DepositNums"`                      //直属充值金额
	Waged                float64 `json:"Waged" db:"Waged" cbor:"Waged"`                                        //直属下级流水
	Commi                float64 `json:"Commi" db:"Commi" cbor:"Commi"`                                        //佣金
	FirstDepositToParent float64 `json:"first_deposit_to_parent" db:"first_deposit_to_parent"`                 //首充梯度奖励佣金
	TotalWithdrawNum     float64 `json:"totalWithdrawNum" db:"totalWithdrawNum"`                               //提现人数
	TotalWithdrawAmount  float64 `json:"totalWithdrawAmount" db:"totalWithdrawAmount"`                         //提现金额
}

type WithdrawItem struct {
	TotalWithdrawNum    float64 `json:"totalWithdrawNum" db:"totalWithdrawNum"`       //提现人数
	TotalWithdrawAmount float64 `json:"totalWithdrawAmount" db:"totalWithdrawAmount"` //提现金额
}

type ProxyDirectChildInfo struct {
	QueryType int32 `json:"QueryType"`
}

func (that ProxyController) QueryProxyDirectChildInfo(ctx *fasthttp.RequestCtx) {
	uid := model.GetUidFromToken(ctx)
	param := ProxyDirectChildInfo{}

	dataBody := ctx.PostBody()
	err := json.Unmarshal(dataBody, &param)
	if err != nil {
		helper.Print(ctx, false, helper.ParamErr)
		return
	}

	var sqlSelect string
	sqlSelect = fmt.Sprintf("select ifnull(sum(team_num),0) as TeamCounts,"+
		"ifnull(sum(first_deposit_num),0) as FirstDepositCounts,"+
		"ifnull(sum(deposit_num),0) as DepositCounts,"+
		"ifnull(sum(deposit),0) as DepositNums,"+
		"ifnull(sum(valid_waged),0) as Waged,"+
		"ifnull(sum(proxy_invite_bonus),0) as Commi, "+
		"ifnull(sum(enable_first_deposit_to_parent),0) as first_deposit_to_parent "+
		"from tbl_report_proxy_daily where uid=%s and level = 1 ", uid)
	var sqlCondition string

	//减去隐藏的充值额
	var sqlSelHiddenDeposit string
	var sqlConHiddenDeposit string
	var sqlSelWithdraw string

	sqlSelHiddenDeposit = fmt.Sprintf("SELECT IFNULL(SUM(hidden_amount), 0) from tbl_deposit where parent_id=%s and (state=362 or state=365) ", uid)
	sqlSelWithdraw = fmt.Sprintf("SELECT IFNULL(SUM(amount), 0) as totalWithdrawAmount,count(DISTINCT uid) as totalWithdrawNum from tbl_withdraw where parent_id=%s and state=374 ", uid)
	if param.QueryType == 1 {
		yesterDay := time.Now().AddDate(0, 0, -1)
		sqlCondition = fmt.Sprintf("and created_at='%s'", yesterDay.Format("2006-01-02"))
		t := time.Now()
		todayEnd := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())
		sqlConHiddenDeposit = fmt.Sprintf("and confirm_at>=%d and confirm_at<%d ", todayEnd.Unix()-24*3600, todayEnd.Unix())
		sqlSelect += sqlCondition
		sqlSelHiddenDeposit += sqlConHiddenDeposit
		sqlSelWithdraw += sqlConHiddenDeposit
	} else if param.QueryType == 2 {
		sqlCondition = fmt.Sprintf("and created_at='%s'", time.Now().Format("2006-01-02"))

		t := time.Now()
		todayBegin := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())
		sqlConHiddenDeposit = fmt.Sprintf("and confirm_at>=%d", todayBegin.Unix())
		sqlSelect += sqlCondition
		sqlSelHiddenDeposit += sqlConHiddenDeposit
		sqlSelWithdraw += sqlConHiddenDeposit
	} else if param.QueryType == 3 {
		now := time.Now()
		daysUntilMonday := int(now.Weekday() - time.Monday)
		if daysUntilMonday < 0 {
			daysUntilMonday += 7
		}

		// 周一的时间
		monday := now.AddDate(0, 0, -daysUntilMonday).Format("2006-01-02") + " 00:00:00"
		t, _ := time.ParseInLocation("2006-01-02 15:04:05", monday, now.Location())

		sqlCondition = fmt.Sprintf("and created_at>='%s'", t.Format("2006-01-02"))

		tWeek := now.AddDate(0, 0, -daysUntilMonday)
		weekBegin := time.Date(tWeek.Year(), tWeek.Month(), tWeek.Day(), 0, 0, 0, 0, t.Location())
		sqlConHiddenDeposit = fmt.Sprintf("and confirm_at>=%d", weekBegin.Unix())
		sqlSelect += sqlCondition
		sqlSelHiddenDeposit += sqlConHiddenDeposit
		sqlSelWithdraw += sqlConHiddenDeposit
	} else if param.QueryType == 4 {

		now := time.Now()
		daysUntilMonday := int(now.Weekday() - time.Monday)
		if daysUntilMonday < 0 {
			daysUntilMonday += 7
		}

		// 周一的时间
		monday := now.AddDate(0, 0, -daysUntilMonday).Format("2006-01-02") + " 00:00:00"
		t, _ := time.ParseInLocation("2006-01-02 15:04:05", monday, now.Location())
		lastWeekMonday := t.AddDate(0, 0, -7)
		sqlCondition = fmt.Sprintf("and created_at>='%s' and created_at<'%s' ", lastWeekMonday.Format("2006-01-02"), t.Format("2006-01-02"))

		tWeek := now.AddDate(0, 0, -daysUntilMonday)
		weekEnd := time.Date(tWeek.Year(), tWeek.Month(), tWeek.Day(), 0, 0, 0, 0, t.Location())
		weekBegin := time.Date(lastWeekMonday.Year(), lastWeekMonday.Month(), lastWeekMonday.Day(), 0, 0, 0, 0, t.Location())

		sqlConHiddenDeposit = fmt.Sprintf("and confirm_at>=%d and confirm_at<%d ", weekBegin.Unix(), weekEnd.Unix())
		sqlSelect += sqlCondition
		sqlSelHiddenDeposit += sqlConHiddenDeposit
		sqlSelWithdraw += sqlConHiddenDeposit
	} else if param.QueryType == 5 {
		MonthStart := helper.MonthSST("", time.Now().Location())
		sqlCondition = fmt.Sprintf("and created_at>='%s'", MonthStart.Format("2006-01-02"))

		MonthBegin := time.Date(MonthStart.Year(), MonthStart.Month(), MonthStart.Day(), 0, 0, 0, 0, time.Now().Location())
		sqlConHiddenDeposit = fmt.Sprintf("and confirm_at>=%d", MonthBegin.Unix())
		sqlSelect += sqlCondition
		sqlSelHiddenDeposit += sqlConHiddenDeposit
		sqlSelWithdraw += sqlConHiddenDeposit
	} else if param.QueryType == 6 {
		MonthStart := helper.MonthSST("", time.Now().Location())
		LastMonthStart := MonthStart.AddDate(0, -1, 0)
		sqlCondition = fmt.Sprintf("and created_at>='%s' and created_at<'%s' ", LastMonthStart.Format("2006-01-02"), MonthStart.Format("2006-01-02"))

		MonthEnd := time.Date(MonthStart.Year(), MonthStart.Month(), MonthStart.Day(), 0, 0, 0, 0, time.Now().Location())
		MonthBegin := time.Date(LastMonthStart.Year(), LastMonthStart.Month(), LastMonthStart.Day(), 0, 0, 0, 0, time.Now().Location())
		sqlConHiddenDeposit = fmt.Sprintf("and confirm_at>=%d and confirm_at<%d ", MonthBegin.Unix(), MonthEnd.Unix())
		sqlSelect += sqlCondition
		sqlSelHiddenDeposit += sqlConHiddenDeposit
		sqlSelWithdraw += sqlConHiddenDeposit
	}

	var dataRet ProxyDirectChildInfoItem
	sqlErr := model.GetSlaveDBInstance().Get(&dataRet, sqlSelect)

	if sqlErr != nil {
		helper.SqlSelectErrLog("QueryTeamData table tbl_report_proxy_daily,%s,\n %s", sqlErr.Error(), sqlSelect)
	}

	var fDepositHidden float64
	sqlErr = model.GetSlaveDBInstance().Get(&fDepositHidden, sqlSelHiddenDeposit)

	if sqlErr != nil {
		helper.SqlSelectErrLog("QueryTeamData table tbl_deposit,%s,\n %s", sqlErr.Error(), sqlSelHiddenDeposit)
	}

	var withdrawData WithdrawItem
	sqlErr = model.GetSlaveDBInstance().Get(&withdrawData, sqlSelWithdraw)

	if sqlErr != nil {
		helper.SqlSelectErrLog("QueryTeamData table tbl_report_proxy_daily,%s,\n %s", sqlErr.Error(), sqlSelect)
	}

	helper.InfoLog("QueryProxyDirectChildInfo:%s", sqlSelect)
	helper.InfoLog("QueryProxyDirectChildInfo1111:%s", sqlSelHiddenDeposit)
	helper.InfoLog("QueryProxyDirectChildInfo2222:%s", sqlSelWithdraw)
	dataRet.DepositNums -= fDepositHidden
	dataRet.TotalWithdrawNum = withdrawData.TotalWithdrawNum
	dataRet.TotalWithdrawAmount = withdrawData.TotalWithdrawAmount
	helper.Print(ctx, true, dataRet)
}

type ChildRunningReturnItem struct {
	ChildRunningReturn float64 `json:"ChildRunningReturn" db:"ChildRunningReturn" cbor:"ChildRunningReturn"`
	ChildCount         float64 `json:"ChildCount" db:"ChildCount" cbor:"ChildCount"`
	VipLevel           int     `json:"VipLevel" db:"VipLevel" cbor:"VipLevel"`
}

type LevelChildRunningReturn struct {
	ChildWagedReturnLevelOne   float64 `json:"ChildWagedReturnLevelOne" db:"ChildWagedReturnLevelOne" cbor:"ChildWagedReturnLevelOne"`
	ChildWagedReturnLevelTwo   float64 `json:"ChildWagedReturnLevelTwo" db:"ChildWagedReturnLevelTwo" cbor:"ChildWagedReturnLevelTwo"`
	ChildWagedReturnLevelThree float64 `json:"ChildWagedReturnLevelThree" db:"ChildWagedReturnLevelThree" cbor:"ChildWagedReturnLevelThree"`
}

func (that ProxyController) QueryChildRunningReturn(ctx *fasthttp.RequestCtx) {
	valUid := model.GetUidFromToken(ctx)

	var tReturnItem ChildRunningReturnItem
	var lelveChildItem LevelChildRunningReturn
	sqlSelect := fmt.Sprintf("select ChildWagedReturnLevelOne,ChildWagedReturnLevelTwo,ChildWagedReturnLevelThree from tbl_member_return where uid=%s", valUid)
	selectErr := model.GetMasterDBInstance().Get(&lelveChildItem, sqlSelect)
	if selectErr != nil {
		helper.InfoLog("[QueryChildRunningReturn:lelveChildItem]:%s error:%s", sqlSelect, selectErr.Error())
	}

	tReturnItem.VipLevel = int(myUserHelp.GetVipLevel(valUid))
	tReturnItem.ChildRunningReturn = lelveChildItem.ChildWagedReturnLevelOne + lelveChildItem.ChildWagedReturnLevelTwo + lelveChildItem.ChildWagedReturnLevelThree
	sqlSelect = fmt.Sprintf("select IFNULL(sum(team_num),0)  from tbl_report_proxy_daily where uid=%s and  level=1 ", valUid)
	selectErr = model.GetSlaveDBInstance().Get(&tReturnItem.ChildCount, sqlSelect)
	if selectErr != nil {
		helper.InfoLog("[QueryChildRunningReturn:ChildCount]:%s error:%s", sqlSelect, selectErr.Error())
	}

	helper.Print(ctx, true, tReturnItem)
}
func (that ProxyController) AchieveChildRunningReturn(ctx *fasthttp.RequestCtx) {
	valUid := model.GetUidFromToken(ctx)
	if valUid == "" {
		helper.Print(ctx, false, errors.New(helper.AccessTokenExpires))
		return
	}

	if myConfig.IsActiveOpen(myConfig.ActiveType_ProxyChildRunningReturn) == 0 {
		helper.Print(ctx, false, helper.AppActiveClose)
		return
	}

	lockKey := valUid + "ChildRunningReturn"
	if !myredis.Lock(model.GetRedisInstance(), lockKey) {
		helper.GetloggerInstance().Criticalf("lockError:%s", lockKey)
		return
	}

	defer myredis.Unlock(model.GetRedisInstance(), lockKey)

	var ChildRunningReturn float64 = 0.00

	var levelChildItem LevelChildRunningReturn
	sqlSelect := fmt.Sprintf("select ChildWagedReturnLevelOne,ChildWagedReturnLevelTwo,ChildWagedReturnLevelThree from tbl_member_return where uid=%s", valUid)
	selectErr := model.GetMasterDBInstance().Get(&levelChildItem, sqlSelect)
	if selectErr != nil {
		helper.InfoLog("[AchieveChildRunningReturn:levelChildItem]:%s error:%s", sqlSelect, selectErr.Error())
	}

	ChildRunningReturn = levelChildItem.ChildWagedReturnLevelThree + levelChildItem.ChildWagedReturnLevelTwo + levelChildItem.ChildWagedReturnLevelOne
	if ChildRunningReturn == 0.0 {
		helper.Print(ctx, true, ChildRunningReturn)
		return
	}

	//增加打码
	sqlUpdate := fmt.Sprintf("update tbl_member_return set  ChildWagedReturnLevelOne = 0.0,ChildWagedReturnLevelTwo = 0.0,ChildWagedReturnLevelThree = 0.0 where uid=%s", valUid)
	_, selectErr = model.GetMasterDBInstance().Exec(sqlUpdate)
	if selectErr != nil {
		helper.InfoLog("[AchieveChildRunningReturn:Exec]:%s error:%s", sqlUpdate, selectErr.Error())
	}

	if levelChildItem.ChildWagedReturnLevelOne > 0.0 {
		myUserHelp.AddBalanceTransactionRecord(valUid, levelChildItem.ChildWagedReturnLevelOne,
			helper.TransactionChildOneWagedReturn, "0", helper.GenId(), 0.00, "", "", 0)
		myUserHelp.AddUserWageItem(valUid, levelChildItem.ChildWagedReturnLevelOne, helper.TransactionChildOneWagedReturn)

		_, errExec := model.GetMasterDBInstance().Exec("CALL tbl_report_proxy_change_update(?,?,?,?)", valUid,
			helper.TransactionChildOneWagedReturn, levelChildItem.ChildWagedReturnLevelOne, time.Now().Unix())
		if errExec != nil {
			helper.GetloggerInstance().Emergencyf("CALL tbl_report_proxy_change_update(%s,%d,%0.2f,%d);	reason:%s",
				valUid, helper.TransactionChildOneWagedReturn, levelChildItem.ChildWagedReturnLevelOne, time.Now().Unix(), errExec.Error())
		}
	}

	if levelChildItem.ChildWagedReturnLevelTwo > 0.0 {
		myUserHelp.AddBalanceTransactionRecord(valUid, levelChildItem.ChildWagedReturnLevelTwo,
			helper.TransactionChildTowWagedReturn, "0", helper.GenId(), 0.00, "", "", 0)
		myUserHelp.AddUserWageItem(valUid, levelChildItem.ChildWagedReturnLevelTwo, helper.TransactionChildTowWagedReturn)

		_, errExec := model.GetMasterDBInstance().Exec("CALL tbl_report_proxy_change_update(?,?,?,?)", valUid,
			helper.TransactionChildTowWagedReturn, levelChildItem.ChildWagedReturnLevelTwo, time.Now().Unix())
		if errExec != nil {
			helper.GetloggerInstance().Emergencyf("CALL tbl_report_proxy_change_update(%s,%d,%0.2f,%d);	reason:%s",
				valUid, helper.TransactionChildTowWagedReturn, levelChildItem.ChildWagedReturnLevelTwo, time.Now().Unix(), errExec.Error())
		}
	}

	if levelChildItem.ChildWagedReturnLevelThree > 0.0 {
		myUserHelp.AddBalanceTransactionRecord(valUid, levelChildItem.ChildWagedReturnLevelThree,
			helper.TransactionChildThreeWagedReturn, "0", helper.GenId(), 0.00, "", "", 0)
		myUserHelp.AddUserWageItem(valUid, levelChildItem.ChildWagedReturnLevelThree, helper.TransactionChildThreeWagedReturn)

		_, errExec := model.GetMasterDBInstance().Exec("CALL tbl_report_proxy_change_update(?,?,?,?)", valUid,
			helper.TransactionChildThreeWagedReturn, levelChildItem.ChildWagedReturnLevelThree, time.Now().Unix())
		if errExec != nil {
			helper.GetloggerInstance().Emergencyf("CALL tbl_report_proxy_change_update(%s,%d,%0.2f,%d);	reason:%s",
				valUid, helper.TransactionChildThreeWagedReturn, levelChildItem.ChildWagedReturnLevelThree, time.Now().Unix(), errExec.Error())
		}
	}

	myUserHelp.AddUserBalanceByFloat64(valUid, ChildRunningReturn)
	helper.Print(ctx, true, ChildRunningReturn)
}

type ChildItemParam struct {
	BeginTime string `json:"beginTime"`
	EndTime   string `json:"endTime"`
	PageIndex int32  `json:"pageIndex"`
	PageCount int32  `json:"pageCount"`
	Uid       int    `json:"Uid"`
}

type ChildItemInfo struct {
	Uid           string  `json:"Uid" db:"uid" cbor:"uid"`
	VipLevel      string  `json:"VipLevel" db:"level" cbor:"level"`                //VIP等级
	DepositAmount float64 `json:"DepositAmount" db:"deposit" cbor:"deposit"`       //充值
	ValidWaged    float64 `json:"ValidWaged" db:"valid_waged" cbor:"valid_waged"`  //有效投注
	TeamCounts    int     `json:"TeamCounts" db:"team_num" cbor:"team_num"`        //直属下级人数
	CreatedAt     int     `json:"CreatedAt" db:"created_at" cbor:"created_at"`     //注册时间
	LastLoginAt   int     `json:"LastLoginAt" db:"last_login_at" cbor:"createdAt"` //最近登陆时间
}

type ChildCollectInfo struct {
	TotalCount int `json:"TotalCount" db:"TotalCount"`
	ListData   []ChildItemInfo

	TeamCounts        int     `json:"TeamCounts" db:"TeamCounts" cbor:"createdAt"`                       //用户数量
	FirstDepositCount float64 `json:"FirstDepositCount" db:"FirstDepositCount" cbor:"FirstDepositCount"` //首次充值数量
	DepositCount      float64 `json:"DepositCount" db:"DepositCount" cbor:"DepositCount"`                //充值人数
	DepositAmount     float64 `json:"DepositAmount" db:"DepositAmount" cbor:"DepositAmount"`             //充值金额
	ValidWaged        float64 `json:"ValidWaged" db:"ValidWaged" cbor:"ValidWaged"`                      //有效投注
}

func (that ProxyController) QueryChildItemInfo(ctx *fasthttp.RequestCtx) {

	uid := model.GetUidFromToken(ctx)
	var dataRet ChildCollectInfo

	param := ChildItemParam{}

	dataBody := ctx.PostBody()
	err := json.Unmarshal(dataBody, &param)
	if err != nil {
		helper.Print(ctx, false, helper.ParamErr)
		return
	}

	var ChildId int = param.Uid
	if ChildId > 0 && (ChildId >= 100000000 || ChildId < 10000000) {
		helper.Print(ctx, true, dataRet)
		return
	}

	//先查询总数
	SelField := "SELECT count(1) FROM `tbl_proxy_base`"
	sqlWhere := fmt.Sprintf("	where parent_id=%s	", uid)
	if ChildId > 0 {
		sqlWhere += fmt.Sprintf("	and uid=%d", ChildId)
	}

	sqlSelect := SelField + sqlWhere

	helper.InfoLog("QueryChildItemInfo 2222 %s", sqlSelect)
	err = model.GetSlaveDBInstance().Get(&dataRet.TotalCount, sqlSelect)

	if dataRet.TotalCount == 0 {
		helper.Print(ctx, true, dataRet)
		return
	}

	SelField = fmt.Sprintf("SELECT a.uid,a.created_at,a.last_login_at,b.level,ifnull(m.deposit,0) as deposit,ifnull(m.valid_waged,0) as valid_waged,ifnull(n.team_num,0) as team_num"+
		"	FROM tbl_member_base as a"+
		"	left join tbl_member_vip as b on a.uid=b.uid"+
		"	left join tbl_proxy_base as c on a.uid=c.uid"+
		"	LEFT JOIN (SELECT uid,ifnull(SUM(deposit),0) AS deposit,ifnull(SUM(valid_waged),0) AS valid_waged FROM tbl_report_user_daily where created_at>='%s' and created_at<='%s'  GROUP BY uid) m"+
		"	on a.uid=m.uid"+
		"	LEFT JOIN (SELECT uid,ifnull(SUM(team_num),0) AS team_num FROM tbl_report_proxy_daily WHERE `level`=1 and  created_at>='%s' and created_at<='%s'  GROUP BY uid) n"+
		"	on a.uid=n.uid", param.BeginTime, param.EndTime, param.BeginTime, param.EndTime)

	sqlWhere = fmt.Sprintf("	where c.parent_id=%s	", uid)
	if ChildId > 0 {
		sqlWhere += fmt.Sprintf("	and a.uid=%d", ChildId)
	}

	sqlSelect = SelField + sqlWhere
	sqlSelect += fmt.Sprintf("  LIMIT %d OFFSET %d", param.PageCount, param.PageIndex*param.PageCount)

	helper.InfoLog("QueryChildItemInfo 2222 %s", sqlSelect)
	err = model.GetSlaveDBInstance().Select(&dataRet.ListData, sqlSelect)
	if err != nil {
		helper.SqlErrLog("QueryChildItemInfo:%s---%s", sqlSelect, err.Error())
	} else {
		helper.InfoLog("QueryChildItemInfo:%s", sqlSelect)
	}

	if len(dataRet.ListData) == 0 {
		helper.Print(ctx, true, dataRet)
		return
	}

	if ChildId == 0 {
		SelField = fmt.Sprintf("SELECT "+
			"	ifnull(sum(team_num),0) as TeamCounts,"+
			"	ifnull(sum(first_deposit_num),0) as FirstDepositCount,"+
			"	ifnull(sum(deposit_num),0) as DepositCount,"+
			"	ifnull(sum(deposit),0) as DepositAmount,"+
			"	ifnull(sum(valid_waged),0) as ValidWaged"+
			"	FROM tbl_report_proxy_daily "+
			"WHERE uid=%s and `level`=1 and  created_at>='%s' and created_at<='%s'", uid, param.BeginTime, param.EndTime)
	} else {
		SelField = fmt.Sprintf("SELECT "+
			"	IFNULL(SUM(CASE WHEN a.first_deposit > 0 THEN 1 ELSE 0 END),0) AS  FirstDepositCount, "+
			"	ifnull(sum(a.deposit_times),0) as DepositCount,"+
			"	ifnull(sum(a.deposit),0) as DepositAmount,"+
			"	ifnull(sum(a.valid_waged),0) as ValidWaged"+
			"	FROM tbl_report_user_daily as a"+
			"	left join tbl_proxy_base as c on a.uid=c.uid"+
			"	where c.uid=%d and a.created_at>='%s' and a.created_at<='%s'", param.Uid, param.BeginTime, param.EndTime)
	}

	sqlSelect = SelField
	helper.InfoLog("QueryChildItemInfo 3333 %s", sqlSelect)
	err = model.GetSlaveDBInstance().Get(&dataRet, sqlSelect)
	if err != nil {
		helper.SqlErrLog("QueryChildItemInfo:%s---%s", sqlSelect, err.Error())
	} else {
		helper.InfoLog("QueryChildItemInfo:%s", sqlSelect)
	}

	if ChildId > 0 && len(dataRet.ListData) > 0 {
		regTime := time.Unix(int64(dataRet.ListData[0].CreatedAt), 0)
		regTimeFormat := regTime.Format("2006-01-02")
		if regTimeFormat >= param.BeginTime && regTimeFormat <= param.EndTime {
			dataRet.TeamCounts = 1
		}
	}

	helper.Print(ctx, true, dataRet)
}
